package com.imu.common.utils;

import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;
import org.apache.commons.lang.StringUtils;

import java.util.regex.Pattern;

public class PhoneUtil {

	private static final Log log = LogFactory.get(PhoneUtil.class);
	private static Pattern xPattern = Pattern.compile("(?:\\(?[0\\+]?\\d{1,3}\\)?)[\\s-]?(?:0|\\d{1,4})[\\s-]?(?:(?:13\\d{9})|(?:\\d{7,8}))");//Pattern.compile("^1\\d{10}$|^852([6|9])\\d{7}$|^886[0][9]\\d{8}$|^853[6]([8|6])\\d{5}$");

	//国内手机号码
	private static Pattern cPattern = Pattern.compile("^((0086)|(86))?[1][0-9]\\d{9}$");

	//港澳台手机号码
	private static Pattern tPattern = Pattern.compile("^(00)?852([6|9])\\d{7}$|^(00)?886[0][9]\\d{8}$|^(00)?853[6]([8|6])\\d{5}$");

	private static PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
	public static boolean isXPhone(String phone){
		if(StringUtils.isEmpty(phone)){
			return false;
		}
		if(!xPattern.matcher(phone).matches()){
			return false;
		}
		return true;
	}

	/**
	 * 港澳台手机号码
	 * @param phone
	 * @return
	 */
	public static boolean isTwPhone(String phone){
		if(StringUtils.isEmpty(phone)){
			return false;
		}
		if(!tPattern.matcher(phone).matches()){
			return false;
		}
		return true;
	}

	/**
	 * 国内手机号码
	 * @param phone
	 * @return
	 */
	public static boolean isCPhone(String phone){
		if(StringUtils.isEmpty(phone)){
			return false;
		}
		if(!cPattern.matcher(phone).matches()){
			return false;
		}
		return true;
	}

	/**
	 * 交易手机号码是否有效
	 * @param phone
	 */
	public static boolean validate(String phone){

		if(StringUtils.isEmpty(phone)){
			return false;
		}
		if(!StringUtils.isNumeric(phone)){
			return false;
		}
		//取前面3或4位，如果为国内手机号码，则不获取
		if(isCPhone(phone)){
			return true;
		}
		boolean phoneFlag = false;
		Phonenumber.PhoneNumber phoneNumber = new Phonenumber.PhoneNumber();
		try {
		    //以下是针对国际号码的处理
		    phone = phone.startsWith("00") ? phone : "00" + phone;
			//取出前三位的 国家编码为001 002
			phoneFlag = checkPhone(phoneNumber, phone, 3);
			if (!phoneFlag) {//0065
				phoneFlag = checkPhone(phoneNumber, phone, 4);
			}
			if (!phoneFlag) {//00852
				phoneFlag = checkPhone(phoneNumber, phone, 5);
			}
		}catch (Exception e){
			log.error(e);
		}
		return phoneFlag;
	}

	private static boolean checkPhone(Phonenumber.PhoneNumber phoneNumber,
									String phone,int location){
		String prefix = phone.substring(0,location);//取出前三位的 国家编码为001 002
		String suffix = phone.substring(location);
		phoneNumber.setCountryCode(Integer.valueOf(prefix));
		phoneNumber.setNationalNumber(Long.valueOf(suffix));
		return phoneNumberUtil.isValidNumber(phoneNumber);
	}
	public static void main(String[] args){
		System.out.println(validate("10000"));
	}

}
